﻿using ECommerce.Web.NHibernate.Sessions.Storage;
using NHibernate;

namespace ECommerce.Web.NHibernate.Sessions
{
    public class SessionSource
    {
        private static readonly SessionSource instance = new SessionSource();

        private ISessionFactory sessionFactory;
        private ISessionStorage sessionStorage;

        static SessionSource() { }
        private SessionSource() { }

        public static SessionSource Current
        {
            get { return instance; }
        }

        public void SetSessionFactory(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }

        public void SetSessionStorage(ISessionStorage sessionStorage)
        {
            this.sessionStorage = sessionStorage;
        }

        public ISession GetSession()
        {            
            ISession session = this.sessionStorage.Session;

            if (session == null)
            {
                session = this.sessionFactory.OpenSession();

                this.sessionStorage.Session = session;
            }

            return session;
        }

        public void CloseSession()
        {
            ISession session = this.sessionStorage.Session;

            if (session != null)
            {
                session.Close();
            }

            this.sessionStorage.RemoveFromStorage();
        }
    }
}
